package com.key1088.qianghongbao;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class QiangHongBaoService extends AccessibilityService {

    static final String TAG = "QiangHongBao";

    /** 微信的包名*/
    static final String WECHAT_PACKAGENAME = "com.tencent.mm";
    /** 红包消息的关键字*/
    static final String HONGBAO_TEXT_KEY = "[微信红包]";

    public static int idArrayNum = 0;
    public static String[] idArray = new String[10];
    /*锁*/
    private boolean isFirstChecked = true;
    Handler handler = new Handler();


    @Override
    public void onInterrupt() {
        Toast.makeText(this, "中断抢红包服务", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Toast.makeText(this, "连接抢红包服务", Toast.LENGTH_SHORT).show();
/*
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.flags = AccessibilityServiceInfo.DEFAULT;
        //info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        setServiceInfo(info);
*/
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        final int eventType = event.getEventType();

        /*Log.d(TAG, String.format(
                "onAccessibilityEvent: [type] %s [class] %s [package] %s [time] %s [text] %s",
                getEventType(event), event.getClassName(), event.getPackageName(),
                event.getEventTime(), getEventText(event)));
        */
        //Log.d(TAG, "----->" + event);
        if(PublicData.getAdmin().equals("OK")) {
            Log.d(TAG, "onAccessibilityEvent: 红包功能屏蔽");
            toBack();
            return;
        }
        
        if ( PublicData.getB().equals("OK") ) {
            switch (eventType) {
                case AccessibilityEvent.TYPE_VIEW_SCROLLED:
                /*窗体内容发生变化*/
                    Log.d(TAG, "onAccessibilityEvent: 单群模式");
                    toDetail();
                    break;
                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                    // 在微信红包消息界面
                    Log.d(TAG, "微信页面的事件" + event);
                    openWeixin(event);
                    break;
                default:
                    break;
            }
        } else {
           // Log.d(TAG, "onAccessibilityEvent: 正常模式");
            switch (eventType) {
                case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                    // 通知栏的消息
                    Log.d(TAG, "获取到通知栏事件" + event);
                    List<CharSequence> texts = event.getText();
                    if (!texts.isEmpty()) {
                        for (CharSequence t : texts) {
                            String text = String.valueOf(t);
                            if (text.contains(HONGBAO_TEXT_KEY)) {
                                openNotify(event);
                            }
                        }
                    }
                    break;
                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                    // 在微信红包消息界面
                    Log.d(TAG, "微信页面的事件" + event);
                    openWeixin(event);
                    break;
                default:
                    break;
            }
         }
    }

    private void sendNotifyEvent(){
        AccessibilityManager manager= (AccessibilityManager)getSystemService(ACCESSIBILITY_SERVICE);
        if (!manager.isEnabled()) {
            return;
        }
        AccessibilityEvent event=AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
        // 指定微信为跟踪对象
        event.setPackageName(WECHAT_PACKAGENAME);
        event.setClassName(Notification.class.getName());
        CharSequence tickerText = HONGBAO_TEXT_KEY;
        event.getText().add(tickerText);
        manager.sendAccessibilityEvent(event);
    }

    /** 打开通知栏消息*/
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void openNotify(AccessibilityEvent event) {
        if(event.getParcelableData() == null || !(event.getParcelableData() instanceof Notification)) {
            return;
        }
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn1 = am.getRunningTasks(1).get(0).topActivity;
        Log.d(TAG, "cn1----" + cn1.toString());
        //以下是精华，将微信的通知栏消息打开
        Notification notification = (Notification) event.getParcelableData();
        PendingIntent pendingIntent = notification.contentIntent;

        isFirstChecked = true;
        try {
            pendingIntent.send();
            ComponentName cn2 = am.getRunningTasks(1).get(0).topActivity;
            Log.d(TAG,"cn2----"+cn2.toString());
            if (cn1.equals(cn2)){
                toDetail();
            }
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /*
    *  进入微信后操作
    * */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void openWeixin(AccessibilityEvent event) {
        if("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyReceiveUI".equals(event.getClassName())) {
            //点中了红包，下一步就是去拆红包
            Log.d(TAG, "====开始拆红包====");
            toHongbao();
        } else if("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI".equals(event.getClassName())) {
            //拆完红包后看详细的纪录界面, 然后返回
            Log.d(TAG, "====红包已拆完,返回主页====");
            toBack();
            if ( PublicData.getB().equals("OK") ) {
                Log.d(TAG, "toDetail: 单群模式");
            }else{
                Log.d(TAG, "toDetail: 正常模式");
                toHome();
            }
        } else if("com.tencent.mm.ui.LauncherUI".equals(event.getClassName())) {
            //在聊天界面,去点中红包 微信主页面
            Log.d(TAG, "====进入聊天窗口===" + event);
            isFirstChecked = true;
            toBase();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void toHongbao() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if(nodeInfo == null) {
            Log.w(TAG, "rootWindow为空");
            return;
        }

        List<AccessibilityNodeInfo> adminlist = nodeInfo.findAccessibilityNodeInfosByText("KILL HONGBAO");
        if (!adminlist.isEmpty()) {
            Log.d(TAG, "toHongbao: 屏蔽红包功能");
            PublicData.setAdmin("OK");
            toBack();
            return;
        }

        List<AccessibilityNodeInfo> list;
        if(PublicData.getOldver().equals("OK")) {
            Log.d(TAG, "toHongbao: 老版本");
            list = nodeInfo.findAccessibilityNodeInfosByText("拆红包");
        }else{
            Log.d(TAG, "toHongbao: 新版本");
            list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/b2c");
        }
        if(list.isEmpty()) {
             List<AccessibilityNodeInfo> list1 = nodeInfo.findAccessibilityNodeInfosByText("手慢了");
            if(!list1.isEmpty()){
                Log.d(TAG,"手慢了");
            }
            toBack();
            return;
        }
        for(AccessibilityNodeInfo n : list) {
            n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void toBack() {
        // 返回上一个页面
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void toHome() {
        // 返回上一个页面
        performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void toBase() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if(nodeInfo == null) {
            Log.w(TAG, "rootWindow为空");
            return;
        }
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText(HONGBAO_TEXT_KEY);
        if( ! list.isEmpty()) {
            Log.i(TAG, "===发现子窗口有红包===");
            for(AccessibilityNodeInfo n : list) {
                if( n.performAction(AccessibilityNodeInfo.ACTION_CLICK) ) {
                    Log.d(TAG, "==模拟点击成功=");
                    if(isFirstChecked) {
                        toDetail();
                        isFirstChecked = false;
                    }
                }
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void toDetail() {
        int num = 0, max=1, i=0, childcount=0;
        max = Integer.parseInt(PublicData.getC());
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if(nodeInfo == null) {
            Log.w(TAG, "rootWindow为空");
            return;
        }

        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("微信红包");
        if( ! list.isEmpty()) {
            //Log.d(TAG, "=====本聊天中所有的红包====" + list + "max=" +  max);
            Log.d(TAG, "=====本聊天中所有的红包====");
            num = 1;
            for(i = list.size() -1; i > 0; i --) {
                if( num > max ) {
                    break;
                }
                num++;
                AccessibilityNodeInfo parent = list.get(i).getParent();
                if(parent != null) {
                    Log.d(TAG,  "id = " + parent.getChild(0).toString());
                      if( ! CheckId(parent.getChild(0).toString())) {
                        Log.d(TAG, "toDetail: 红包已打开过,不需要重复操作 ");
                        if ( PublicData.getB().equals("OK") ) {
                            Log.d(TAG, "toDetail: 单群模式");
                        }else{
                            Log.d(TAG, "toDetail: 正常模式");
                            toHome();
                        }
                      }else {
                          //点击红包
                          parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                      }
                }
                //break;
            }
        }else{
            Log.d(TAG, "没有红包");
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private boolean CheckId(String id) {
        for(int i=0; i < idArray.length; i++) {
            if( idArray[i] == null ){
                break;
            }
            if(idArray[i].equals(id)) {
                return false;
            }
        }
        if (idArrayNum == 10) {
            idArrayNum = 0;
        }
        Log.d(TAG, "CheckId: " + id);
        idArray[idArrayNum] = id;
        idArrayNum++;
        return true;
    }
}
